//
//  LoginHelper.m
//  Lovely Food
//
//  Created by 李经纬 on 15/12/1.
//  Copyright © 2015年 李经纬. All rights reserved.
//

#import "LoginHelper.h"
#import <AVOSCloud.h>
#import "AppDelegate.h"
#import "Header.h"


@implementation LoginHelper

// 登陆
- (void)loginWithUserName:(NSString *)userName passWord:(NSString *)passWord
{
    [AVUser logInWithUsernameInBackground:userName password:passWord block:^(AVUser *user, NSError *error) {
        
        // 登陆成功判断
        if (user !=nil && error == nil) {
            // 跳转到主页面
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            RootViewController *rootVC = [[RootViewController alloc] init];
            app.window.rootViewController = rootVC;
            
            // 单例存储用户的信息
            [[UserManaged defaultManager] saveUserName:userName userId:user.objectId];
            
            
            // 存储到本地
            NSUserDefaults *myUser = [NSUserDefaults standardUserDefaults];
            [myUser setObject:userName forKey:@"userName"];
            [myUser setObject:user.objectId forKey:@"userId"];
            [myUser synchronize];
            
        } else {
            
            if (self.delegate != nil && [self.delegate respondsToSelector:@selector(promptView)]) {
                [self.delegate promptView];
            }
        }
        
        
        
    }];
}

// 注册
- (void)registeWithUserName:(NSString *)userName passWord:(NSString *)passWord email:(NSString *)email phone:(NSString *)phone
{
    AVUser *user = [AVUser user];
    user.username = userName;
    user.password = passWord;
    user.email = email;
    float kCompressionQuality = 0.1;
    NSData *dataImage = UIImageJPEGRepresentation([UIImage imageNamed:@"touxiang"], kCompressionQuality);
    AVFile *imageFile = [AVFile fileWithName:@"image.png" data:dataImage];
    [imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            
            
            [user setObject:phone forKey:@"phone"];
            [user setObject:@"0" forKey:@"follow"];
            [user setObject:@"北京 海淀" forKey:@"address"];
            [user setObject:@"男" forKey:@"gender"];
            [user setObject:@"源于最爱" forKey:@"sdasd"];
            [user setObject:imageFile forKey:@"headImage"];
            
            
            [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    [self loginWithUserName:userName passWord:passWord];
                } else {
                    if ([error.userInfo[@"error"] isEqualToString:@"The email address was invalid."]) {
                        self.passChange();
                    }
                    NSLog(@"%@",error);
                    
                }
                
                
                
            }];

            
        } else {
            NSLog(@"%@",error);
        }
    }];
    
    
    
    
    
}
@end
